package algorithm.leetcode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wuwen
 * @since 2023/12/18
 */
public class NO49_字母异位词分组 {
    public static void main(String[] args) {
        String[] param = {"sfsdfasdf", "sdsfsfs"};
        List<List<String>> lists = new SolutionConcise().groupAnagrams(param);
        System.out.println(lists);
    }

    static class Solution {
        public List<List<String>> groupAnagrams(String[] handles) {
            Map<Character, Integer> charToPrime = Map.of('a', 2, 'b', 3, 'c', 5, 'd', 7, 'e', 11, 'f', 13, 'g', 17, 'h', 19, 'i', 23, 'j', 29);
            System.out.println();
            Map<String, List<String>> grouper = new HashMap<>();
            for (String handle : handles) {
                String key = hash(handle);
                // 如果key对应的value为空则，自己拆入，否则连接到后面
                List<String> value = grouper.getOrDefault(key, new ArrayList<>());
                value.add(handle);
                grouper.put(key, value);
            }
            return new ArrayList<>(grouper.values());
        }

        private String hash(String handle) {
            char[] temp = handle.toCharArray();
            Arrays.sort(temp);
            return Arrays.toString(temp);
        }
    }

    /**
     * 一个很简洁的处理方法
     */
    static class SolutionConcise {
        public List<List<String>> groupAnagrams(String[] handles) {
            return new ArrayList<>(Arrays.stream(handles).collect(Collectors.groupingBy(s -> s.chars().sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString())).values());
        }
    }


}


